package mspbots.data.tl.prod.autotask.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultEntity;
import mspbots.data.tl.prod.autotask.mapper.TaskAutotaskServiceCallTicketResourcesMapper;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskServiceCallTicketResources;
import mspbots.data.tl.prod.autotask.service.TaskAutotaskServiceCallTicketResourcesService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;

@Service
@Log4j2
@RequiredArgsConstructor
@DS("master")
public class TaskAutotaskServiceCallTicketResourcesServiceImpl extends AbstractBaseServiceImpl<TaskAutotaskServiceCallTicketResourcesMapper, TaskAutotaskServiceCallTicketResources>
        implements TaskAutotaskServiceCallTicketResourcesService {

    private final TaskAutotaskServiceCallTicketResourcesMapper taskAutotaskServiceCallTicketResourcesMapper;

    @Override
    public void sync(ResultEntity content){
        log.info("Auto task serviceCallTicketResources receiver content{}",content);
        JsonNode entity = content.getEntity();
        TaskAutotaskServiceCallTicketResources data=TaskAutotaskServiceCallTicketResources.builder()
                .serviceCallTicketResourcesId(super.getLongValue(entity.get("id")))
                .resourceId(ObjectUtils.isEmpty(entity.get("resourceID")) ? null : entity.get("resourceID").asInt())
                .serviceCallTaskId(super.getIntegerValue(entity.get("serviceCallTicketID")))
                .syncTime(LocalDateTime.now())
                .build();
        data.setTenantCode(content.getTenantId());

        TaskAutotaskServiceCallTicketResources dbData = super.baseMapper.selectOne(Wrappers.<TaskAutotaskServiceCallTicketResources>lambdaQuery()
                .eq(TaskAutotaskServiceCallTicketResources::getTenantCode, data.getTenantCode())
                .eq(TaskAutotaskServiceCallTicketResources::getServiceCallTicketResourcesId, data.getServiceCallTicketResourcesId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)){
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }


    }

}
